package com.lyf.language.learn.atsgg.network;

import org.junit.Test;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

/**
 * @AUTHOR LYF
 * @DATE 2022/6/4
 * @VERSION 1.0
 * @DESC
 * UDP:只管发，发生IP+PORT封装在UDP包中
 */
public class UdpTests {
    @Test
    public void sender(){

        DatagramSocket socket = null;
        String data = "udp hhh";
        try {
            socket = new DatagramSocket();
            DatagramPacket datagramPacket = new DatagramPacket(data.getBytes(StandardCharsets.UTF_8),0,data.length(),
                    InetAddress.getLocalHost(),8899);
            socket.send(datagramPacket);//datagramPacket.getLength()

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            assert socket != null;
            socket.close();
        }

    }

    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(8899);
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
        socket.receive(datagramPacket);
        System.out.println(datagramPacket.getData().toString());
    }
}
